package com.ysxsoft.wdg.ui.fragment.order;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.classic.common.MultipleStatusView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.adapter.order.OnOrderClickListener;
import com.ysxsoft.wdg.adapter.order.ZyOrderAdapter;
import com.ysxsoft.wdg.adapter.order.ZyOrderDetailActivity;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.bean.BaseBean;
import com.ysxsoft.wdg.bean.ZyOrderBean;
import com.ysxsoft.wdg.bean.cart.ShopcartBean;
import com.ysxsoft.wdg.bean.response.CollectShopResponse;
import com.ysxsoft.wdg.bean.response.ShouResponse;
import com.ysxsoft.wdg.net.CallbackCode;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.ui.activity.order.AplyBackOrderActivity;
import com.ysxsoft.wdg.ui.activity.order.BackOrderDetailActivity;
import com.ysxsoft.wdg.ui.activity.order.EmsActivity;
import com.ysxsoft.wdg.ui.activity.order.ZyOrderPlActivity;
import com.ysxsoft.wdg.util.JsonUtils;
import com.ysxsoft.wdg.util.ListObserverMap;
import com.ysxsoft.wdg.util.ToastUtils;
import com.ysxsoft.wdg.util.sp.SharePrefUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.Call;

public class OrderMjFragment extends BaseFragment implements OnRefreshListener, OnLoadmoreListener,ListObserverMap.IListDataChangeObserver {

    @BindView(R.id.tv_all)
    TextView tvAll;
    @BindView(R.id.tv_fk)
    TextView tvFk;
    @BindView(R.id.tv_fh)
    TextView tvFh;
    @BindView(R.id.tv_sh)
    TextView tvSh;
    @BindView(R.id.tv_pj)
    TextView tvPj;
    @BindView(R.id.tv_tk)
    TextView tvTk;
    @BindView(R.id.recyclerview)
    RecyclerView recyclerview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.multStatusView)
    MultipleStatusView multStatusView;

    private TextView[] textViews;
    private String style = "3";//满减订单
    //type0全部1待付款2待发货3待收货4待评价5退款
    private int page = 1, type = 0;
    private int clickPosition;
    private ZyOrderAdapter mAdapter;
    private List<ZyOrderBean> list;

    @Override
    protected int getLayoutId() {
        return R.layout.fm_order_zy;
    }

    @Override
    protected void initData() {
        textViews = new TextView[]{tvAll,tvFk,tvFh,tvSh,tvPj,tvTk};
        setSelector(0);
        list = new ArrayList<>();
        recyclerview.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter = new ZyOrderAdapter(list, mContext);
        mAdapter.setStatus(true);
        recyclerview.setAdapter(mAdapter);
        onRefresh(refreshLayout);
        ListObserverMap.reg("OrderMjFragment",this);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ListObserverMap.remove("OrderMjFragment");
    }

    @Override
    protected void setListener() {
        refreshLayout.setOnLoadmoreListener(this);
        refreshLayout.setOnRefreshListener(this);
        mAdapter.setOnOrderClickListener(new OnOrderClickListener() {
            @Override
            public void OnLeftClickListener(int type, int position) {
                clickPosition = position;
                if (list.size() < position) {
                    return;
                }
                ZyOrderBean order = list.get(position);
                switch (type) {  //0未付1已付，待发货2已发货，待收货3已收货，待评价4完成5退款售后6退款成功
                    case 0://取消订单
                        cancelOrder(order.getOrderid());
                        break;
                    case 1://退款
                        AplyBackOrderActivity.start(getActivity(), order.getOrderid(), 1,true);
                        break;
                    case 2://查看物流
                        Intent intent2 = new Intent(getActivity(), EmsActivity.class);
                        intent2.putExtra("emsNo",order.getKd_no());
                        intent2.putExtra("emsTypeCode",order.getKd_type());
                        startActivity(intent2);
                        break;
                    case 3://查看物流
                        Intent intent = new Intent(getActivity(), EmsActivity.class);
                        intent.putExtra("emsNo",order.getKd_no());
                        intent.putExtra("emsTypeCode",order.getKd_type());
                        startActivity(intent);
                        break;
                    case 4://删除订单
                        break;
                }
            }

            @Override
            public void OnRightClickListener(int type, int position) {
                clickPosition = position;
                ZyOrderBean order = list.get(position);
                switch (type) {//0未付1已付，待发货2已发货，待收货3已收货，待评价4完成5退款售后6退款成功
                    case 0://立即支付
                        ZyOrderDetailActivity.start(mContext, list.get(position).getOrderid(),false);
                        break;
                    case 1://提醒发货
                        notifyOrder(order.getOrderid());
                        break;
                    case 2://确认收货
                        shou(order.getOrderid());
                        break;
                    case 3://立即评价
                        if(order.getDetail()!=null&&order.getDetail().size()>0){
                            ShopcartBean shopcartBean=order.getDetail().get(0);
                            ZyOrderPlActivity.start(getActivity(),shopcartBean.getProductid()+"",order.getOrderid(),0,false);
                        }
                        break;
                    case 5://查看详情
                    case 6:
                        BackOrderDetailActivity.startByMj(mContext,list.get(position).getOrderid());
                        break;
                }
            }

            @Override
            public void OnItemClickListener(int position) {
                clickPosition=position;

                int status=list.get(position).getStatus();
//                if(status==5||status==6||status==7){
//                    BackOrderDetailActivity.start(mContext, list.get(position).getOrderid());
//                }else{
                    ZyOrderDetailActivity.start(mContext, list.get(position).getOrderid(),false);
//                }
            }
        });
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (resultCode) {
//            case Activity.RESULT_OK:
//                if(data!=null){
//                    if (requestCode == 0x03 ) {//满减立即评价
//                        Log.e("tag","满减立即评价");
//                        list.get(clickPosition).setDiscuss("1");
//                        mAdapter.notifyItemChanged(clickPosition);
//                    }
//                }
//                break;
//        }
//    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        refreshlayout.finishLoadmore(500);
        page++;
        getList();
    }

    @Override
    public void onResume() {
        super.onResume();
        page=1;
        getList();
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        refreshlayout.finishRefresh(500);
        page = 1;
        list.clear();
        mAdapter.clear();
        getList();
    }

    @OnClick({R.id.tv_all, R.id.tv_fk, R.id.tv_fh, R.id.tv_sh,
            R.id.tv_pj, R.id.tv_tk})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_all:
                setSelector(0);
                break;
            case R.id.tv_fk:
                setSelector(1);
                break;
            case R.id.tv_fh:
                setSelector(2);
                break;
            case R.id.tv_sh:
                setSelector(3);
                break;
            case R.id.tv_pj:
                setSelector(4);
                break;
            case R.id.tv_tk:
                setSelector(5);
                break;
        }
        onRefresh(refreshLayout);
    }

    public void setSelector(int position){
        for (int i = 0; i < textViews.length; i++) {
            if (position == i){
                textViews[i].setSelected(true);
            }else {
                textViews[i].setSelected(false);
            }
        }
        type=position;
    }

    private void getList() {
        mApiHelper.getZyOrderList(SharePrefUtils.getUserId(), page + "", type + "", style, new Observer<BaseBean<List<ZyOrderBean>>>() {
            @Override
            public void onSubscribe(Disposable d) {
            }

            @Override
            public void onNext(BaseBean<List<ZyOrderBean>> baseBean) {
                if (baseBean.getCode().equals(CallbackCode.SUCCESS)) {
                    multStatusView.showContent();

                    if (page == 1) {
                        list = baseBean.getData();
                    } else {
                        list.addAll(baseBean.getData());
                    }

                    mAdapter.setData(list);

                } else {
                    ToastUtils.showToast(baseBean.getMs());
                    if (page == 1) {
                        multStatusView.showEmpty();
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                multStatusView.showError();
            }

            @Override
            public void onComplete() {

            }
        });
    }

    /**
     * 取消订单
     */
    private void cancelOrder(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.CANCEL_ORDER)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("type", "1")//1自营2实体
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        ToastUtils.showToast(collectShopResponse.getMs());
                        mAdapter.notifyItemRemoved(clickPosition);
//                        mAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 通知发货
     */
    private void notifyOrder(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.NOTIFY_SHOP)
                .addParams("uid", SharePrefUtils.getUserId())
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    CollectShopResponse collectShopResponse = JsonUtils.parseByGson(response, CollectShopResponse.class);
                    if (collectShopResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(collectShopResponse.getCode())) {
                        ToastUtils.showToast(collectShopResponse.getMs());
//                        mAdapter.notifyItemRemoved(clickPosition);
//                        mAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.showToast(collectShopResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    /**
     * 确认收货
     */
    private void shou(String orderId) {
        OkHttpUtils.post()
                .url(UrlHost.SHOU)
                .addParams("type","2")//自营商城1满减2
                .addParams("orderid", orderId)//订单id
                .tag(this)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (!call.isCanceled()) {
                }
            }

            @Override
            public void onResponse(String response, int id) {
                if (response != null) {
                    ShouResponse shouResponse = JsonUtils.parseByGson(response, ShouResponse.class);
                    if (shouResponse == null) {
                        return;
                    }
                    if (CallbackCode.SUCCESS.equals(shouResponse.getCode())) {
                        ToastUtils.showToast(shouResponse.getMs());
//                        mAdapter.notifyItemRemoved(clickPosition);
                        page = 1;
                        getList();
                    } else {
                        ToastUtils.showToast(shouResponse.getMs());
                    }
                } else {
                }
            }
        });
    }

    @Override
    public void ping() {
        //自营商品评论成功
        if(list!=null&&list.size()>clickPosition){
            list.get(clickPosition).setDiscuss("1");
            mAdapter.notifyItemChanged(clickPosition);
        }
    }

    @Override
    public void pay() {
        //详情支付成功
        page=1;
        getList();
    }

    @Override
    public void cancel() {
        //详情取消订单
        if(list!=null&&list.size()>clickPosition){
            mAdapter.notifyItemRemoved(clickPosition);
        }
    }
}
